#!/bin/bash 
#
# Copyright (c) 2007-2008 The PureDarwin Project.
# All rights reserved.
#
# @LICENSE_HEADER_START@
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# @LICENSE_HEADER_END@
#

#
# Remove installed projects based on darwinbuild receipts
#

RECEIPTSPATH=/usr/local/darwinbuild/receipts
RECEIPT=$RECEIPTSPATH/$1

# Check whether the name of a project has been supplied and exit otherwise
if [ ! $1 ]; then
	echo "Usage: $(basename $0) project"
	exit 1
fi

# Check whether there is a receipt and exit otherwise
if [ ! -f "$RECEIPT" ]; then
	echo "$1 seems not to be installed."
	echo "Not found: $RECEIPT"
	exit 1
fi

# Delete files and symlinks first
while read x mod owner group y filename
do
if [ -f "$filename" -o -L "$filename" ]; then
rm "$filename"
fi
done <<EOF
$(cat $RECEIPT | sed "s|./|/|" )
EOF

# Delete empty directories then
while read mod owner group y filename
do
if [ -d "$filename" ]; then
rmdir -p "$filename/" 2>/dev/null
fi
done <<EOF
$(cat $RECEIPT | sed "s|./|/|" )
EOF

# Find original receipt
ORIGINAL=$(ls -l $RECEIPT | cut -d ">" -f 2 | sed "s/\ //")

# Delete receipt and link to it
rm -f "$RECEIPT" "$RECEIPTSPATH/$ORIGINAL"

echo "$1 removed."
